const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const {expressjwt} = require('express-jwt');
const fs = require('fs');
const base64 = require('base-64');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const apiRouter = require('./routes/api');
const config = require('./router_handler/config');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 响应错误的模板中间件
app.use((req,res,next)=>{
  // status默认值为1,表示失败
  // err是一个错误的对象
  res.cc = function(err,status = 1){
    res.send({
      status:status,
      msg:err instanceof Error ? err.message : err,
    })
  };
  next();
});

//  配置token解析的中间件
app.use(expressjwt({secret:config.jwtSecretKey,algorithms:['HS256']})
.unless({path:[/^\/users\//]}));


app.use('/index', indexRouter);
app.use('/users', usersRouter);
app.use('/api',apiRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  if (err.name === 'UnauthorizedError') {
    res.cc("token认证失败",1)
  }
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

process.env.PORT = 8888;

module.exports = app;
